package org.neptune.service.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author lwl
 * @date 2019/7/24 11:31
 */
@Component
public class SpringApplicationContext implements ApplicationContextAware {

	private static final Logger logger = LoggerFactory.getLogger(SpringApplicationContext.class);

	// 双重入锁 单例
	// 内存模型 重排序 可见性
	private static volatile ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// 持有类锁
		synchronized (SpringApplicationContext.class){
			if (SpringApplicationContext.applicationContext == null){
				logger.info("********** init application cntext util **********");
				SpringApplicationContext.applicationContext = applicationContext;
			}
		}
	}

	public static <T> T getBeanByClass(Class<T> clazz) {
		return applicationContext.getBean(clazz);
	}

	public static Object getBeanByName(String name) {
		return applicationContext.getBean(name);
	}
}
